/**
 * Created by wcy on 2016/8/14.
 */
var fs = require( 'fs' );
var express = require('express');
var mysql = require('../conf/mysql.js');
var router = express.Router();


var app = require('http').createServer(handler),
    io = require('socket.io').listen(app);
app.listen(8888);

router.get('/',function(req,res,next){
    res.render("chat/chat")
})
function handler (req, res) {
    fs.readFile(__dirname + '/index.html',function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data);
    });
}
//�����û�
var onlineUser=new  Array();
var onlineCount=0;
var count=0;
io.on("connection",function(socket){
    console.log("连接成功")
    var data='[{"msg":"连接成功","code":"1"}]';
    //群发
    socket.emit('server', { data:data,userCount:count,onlineUserCount:onlineUser});//链接服务

    //群发
    socket.on("message",function(data){
        console.log(111)
        var msg=data["msg"];
        var name=data["name"];
        if(onlineUser.indexOf(name)>=0){
            io.emit('message', { msg: msg,userCount:count,name:name});
        }
        else{
            io.emit('error', { code:11});
        }
    })
    //登录
    socket.on("login",function(data){
        var name=data["name"];
        var pass=data["pwd"];
        var conn=mysql.connect();
        mysql.login(conn,name,pass,function(res){
            if(res[0]){
                var id=res[0]["id"];
                if(onlineUser.indexOf(res[0]["username"])<0){
                    onlineUser.push(res[0]["username"]);
                    count++;
                }
                io.emit("login",{data:res[0],code:10,userCount:count,onlineUserCount:onlineUser});
            }else{
                io.emit("login",{code:11});
            }
        })
    })
    socket.on("exit",function(data){
        var name=data["name"];
        onlineUser.pop(name);
        count--;
        io.emit("exit",{name:name,userCount:count,onlineUserCount:onlineUser});
    })
})
module.exports=router;

